<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input v-model="queryParams.keywords" placeholder="日志内容" clearable @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item prop="createTime" label="操作时间">
          <el-date-picker v-model="queryParams.createTime" :editable="false" type="daterange" range-separator="~"
            start-placeholder="开始时间" end-placeholder="截止时间" value-format="YYYY-MM-DD" style="width: 200px" />
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <el-table v-loading="loading" :data="pageData" highlight-current-row class="data-table__content">
        <el-table-column label="操作时间" prop="createTime" width="180" />
        <el-table-column label="操作人" prop="operator" width="120" />
        <el-table-column label="日志模块" prop="module" width="100" />
        <el-table-column label="日志内容" prop="content" min-width="200" />
        <el-table-column label="IP 地址" prop="ip" width="150" />
        <el-table-column label="地区" prop="region" width="150" />
        <el-table-column label="浏览器" prop="browser" width="150" />
        <el-table-column label="终端系统" prop="os" width="200" show-overflow-tooltip />
        <el-table-column label="执行时间(ms)" prop="executionTime" width="150" />
        <el-table-column label="操作" fixed="right" width="90">
          <template #default="{ row }">
            <el-button type="primary" size="small" link icon="search" @click="handleViewDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="fetchData" />
    </el-card>

    <el-drawer v-model="drawerVisible" size="50%" title="日志详情" :with-header="true">
      <el-scrollbar class="detail-scroll" v-loading="detailLoading">
        <el-descriptions v-if="currentRow" :column="2" border size="small" class="log-detail-descriptions">
          <el-descriptions-item label="日志模块">
            {{ currentRow.module || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="日志内容" :span="2">
            {{ currentRow.content || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="请求方式">
            {{ currentRow.requestMethod || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="请求路径" :span="2">
            {{ currentRow.requestUri || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="方法名" :span="2">
            {{ currentRow.method || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="请求参数" :span="2">
            <div>{{ formatJson(currentRow.requestParams) }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="返回参数" :span="2">
            <div>{{ formatJson(currentRow.responseContent) }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="IP 地址">
            {{ currentRow.ip || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="省份">
            {{ currentRow.province || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="城市">
            {{ currentRow.city || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="浏览器">
            {{ currentRow.browser || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="浏览器版本">
            {{ currentRow.browserVersion || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="终端系统">
            {{ currentRow.os || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="执行时间(ms)">
            {{ currentRow.executionTime ?? "-" }}
          </el-descriptions-item>
          <!-- <el-descriptions-item label="创建人 ID">
            {{ currentRow.createBy || "-" }}
          </el-descriptions-item> -->
          <el-descriptions-item label="创建人">
            {{ currentRow.operator || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ currentRow.createTime || "-" }}
          </el-descriptions-item>
        </el-descriptions>

        <el-empty v-else-if="!detailLoading" description="暂无数据" />
      </el-scrollbar>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Log",
  inheritAttrs: false,
});

import { ElMessage } from "element-plus";
import LogAPI, { LogPageVO, LogPageQuery, LogDetailVO } from "@/api/system/log.api";

const queryFormRef = ref();

const loading = ref(false);
const total = ref(0);

const queryParams = reactive<LogPageQuery>({
  pageNum: 1,
  pageSize: 10,
  keywords: "",
  createTime: ["", ""],
});

// 日志表格数据
const pageData = ref<LogPageVO[]>([]);

// 抽屉详情
const drawerVisible = ref(false);
const detailLoading = ref(false);
const currentRow = ref<LogDetailVO | null>(null);

/** 获取数据 */
function fetchData() {
  loading.value = true;
  LogAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 查询（重置页码后获取数据） */
function handleQuery() {
  queryParams.pageNum = 1;
  fetchData();
}

/** 重置查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.createTime = undefined;
  fetchData();
}

/** 查看详情 */
function handleViewDetail(row: LogPageVO) {
  drawerVisible.value = true;
  detailLoading.value = true;
  currentRow.value = null;
  LogAPI.getDetail(row.id)
    .then((data) => {
      currentRow.value = data;
    })
    .catch(() => {
      ElMessage.error("获取日志详情失败");
    })
    .finally(() => {
      detailLoading.value = false;
    });
}

/**
 * 格式化 JSON 字符串，便于展示
 */
function formatJson(value?: string) {
  if (!value) return "-";
  try {
    const parsed = JSON.parse(value);
    return JSON.stringify(parsed, null, 2);
  } catch (error) {
    return value;
  }
}

onMounted(() => {
  handleQuery();
});
</script>
